define("data-collection", ['echarts', 'vw.searchtree', 'vw.edittable', 'bootstrap.wizard', 'bootstrap.validator-cn', 'bootstrap.fileinput-cn'], function(echarts) {
	"use strict";
	var _uid, _fid, _uName;
	var $searchtree, $searchtreeTable, breadcrumbID, $selectPeriod, $wizard, $alertMsg;
	var $tableStat, $edittable, $tableAttach, $formMeta;
	var _object, _table, _loadedNodeID, _idField;
	var _stateNum, _passCheck;

	function Init() {
		_uid = vw_static.getCookie(window.location.host);
		_fid = vw_static.getQueryString(window, "fid");
		_uName = vw_static.getCookie(_uid).split('|')[0];

		$searchtree = $('#vw-searchtree');
		$searchtreeTable = $('#vw-searchtree-table');
		breadcrumbID = 'vw-breadcrumb';
		$selectPeriod = $('#selectPeriod');
		$wizard = $('#rootwizard');
//		$alertMsg = $('#alertMsg');
		$tableStat = $('#table_stat');
		$edittable = $('#table_data');
		$tableAttach = $('#table_attach');
		$formMeta = $('#form_meta');

		resize();
		$(window).resize(resize);

		getyear();
		getCheckStat("数据状态");
		initPeriod();
		
		initWizard();
		initTree();
	}

	function resize() {
		$(".vw-left-container").css("height", $(window).height() - 300 + "px");
		$(".vw-content-container").css("height", $(window).height() - 45 + "px");
		$formMeta.css({
			"overflow-x": "hidden",
			"overflow-y": "auto",
			"max-height": $(".vw-content-container").height() - 140 + "px"
		});
		$searchtreeTable.css("height", 190 + "px");
	}

	function initWizard() {
		$wizard.bootstrapWizard({
			'tabClass': 'bwizard-steps',
			'nextSelector': '.button-next',
			'previousSelector': '.button-previous',
			onTabClick: function(tab, navigation, currentIndex, index) {
				return switchTab(index);
			},
			onPrevious: function(tab, navigation, index) {
				if(index == 0) {
					return switchTab(index);
				}
			},
			onNext: function(tab, navigation, index) {
				if(index == 2) {
					return switchTab(index);
				}
			}
		});

		function switchTab(index) {
			if($edittable.html() && $edittable.vw_edittable('hasUncommitData')) {
				bDialog.alert('您有尚未保存的数据，切换后数据将丢失，是否仍要跳转？', function() {
					showTab(index);
					$wizard.bootstrapWizard('show', index);
				}, {
					messageType: 'confirm',
					cancel: function() {}
				});
				return false;
			} else {
				showTab(index);
				return true;
			}
		}

		function showTab(index) {
			$edittable.vw_edittable('destroy');
			if(index == 0) {
				InitTab1();
			} else if(index == 1) {
				InitTab2();
			} else if(index == 2) {
				InitTab3();
			} else if(index == 3) {
				InitTab4();
			} else {}
		}
	}

	function initPeriod() {
		$selectPeriod.select2({
			placeholder: "请选择...",
			language: "zh-CN"
		});

		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.CollectionManage("GetPeriod"),
			type: "get",
			dataType: "json",
		}, function(e) {
			for(var i = 0; i < e.data.length; i++) {
				$selectPeriod.append('<option value="' + e.data[i].id + '">' + e.data[i].text + '</option>');
			};

			$selectPeriod.on('select2:select', function(e) {
				if(!_object) {
					$.Notify({
						caption: "提示",
						content: "请选择报表",
						type: "info"
					});
					return;
				}
				InitTableList();
			});
		});
	}

	function initTree() {
		$searchtree.vw_searchtree({
			breadcrumbID: breadcrumbID,
			$container: $(".vw-left-container"),
			//			levels: 4,
			dataurl: VW_INTERFACE.WEBSERVICE.CollectionManage("GetCatalog"),
			extrapara: {
				userID: _uid,
				functionID: _fid
			},
			onTreeSelected: function(node) {
				if(!$selectPeriod.select2('val')) {
					$.Notify({
						caption: "提示",
						content: "请选择调查期",
						type: "info"
					});
					return;
				}
				_object = node;
				_table = undefined;
				InitTableList();
			}
		});
	}

	function InitTableList() {
		$searchtreeTable.vw_searchtree('destroy');
		$tableStat.vw_edittable('destroy');
		if(_object) {
			$searchtreeTable.vw_searchtree({
				height: $searchtreeTable.height() + 50,
				showSearch: false,
				dataurl: VW_INTERFACE.WEBSERVICE.CollectionManage("GetTables"),
				extrapara: {
					"table": _object.id,
					"userID": _uid,
					"period": $selectPeriod.val()
				},
				onTreeSelected: function(table) {
					if(!table.isChild) {
						refresh(function() {
							_table = table;
							InitTab1();
						});
					} else {
						refresh(function() {
							_table = undefined;
						});
					}
				},
			})
		}

		function refresh(fn) {
			if($edittable.html() && $edittable.vw_edittable('hasUncommitData') && _table && _loadedNodeID == _table.id) {
				bDialog.alert('您有尚未保存的数据，切换后数据将丢失，是否仍要跳转？', function() {
					fn();
				}, {
					messageType: 'confirm',
					cancel: function() {
						if(_table) {
							$searchtree.vw_searchtree('SelectNode', _table.id, true);
						}
					}
				});
			} else {
				fn();
			}
		}
	}

	function InitTab1() {
//		$alertMsg.html("");
		$tableStat.vw_edittable('destroy');

		if(!_table) {
			return;
		}
		$wizard.bootstrapWizard('show', 0);

		$tableStat.vw_edittable({
			type: "table",
			showNewData: false,
			showErrorlog: false,
			showEdit: false,
			ExtraTools: '<button type="button" id="btn_reupload" class="btn btn-warning">申请重新上报</button>',
			columnFormatter:_columnFormatter,
			extrapara: {
				"catalogID": _object.id,
				"userID": _uid,
				"period": $selectPeriod.val(),
				"year": _year.currentYear
			},
			$container: $(".vw-content-container"),
			heightDiff: 130,
			dataURL: VW_INTERFACE.WEBSERVICE.CollectionManage("ExamineLog"),
			onInitialized: function() {
				$('#btn_reupload').click(btn_reupload);
			},
			onDataLoaded: function(data) {
				_passCheck = false;
				if(data && data.data[0] && data.data[0]['调查对象状态']) {
					$.each(_checkStatEnum, function(k, val) {
						if(k === data.data[0]['调查对象状态']) {
							_passCheck = (val.id < 10 && val.id > 1) || val.id == 0;
						}
					});
				}
				$('#btn_reupload').prop('disabled', !_passCheck);
			}
		}).vw_edittable('ajaxLoadTableData', _table.id, _table.text, 1);
	}

	function InitTab2() {
//		if(!_passCheck) {
//			$alertMsg.html("请导入数据并根据提示修改错误信息，导入数据前请确认数据与模板文件是否一致。");
//		}

		$edittable.vw_edittable('destroy');

		if(!_table) {
			return;
		}

		$edittable.vw_edittable({
			type: _table.hasHtml ? "report" : "table",
			showNewData: !_passCheck,
			showErrorlog: !_passCheck,
			showEdit: !_passCheck,
			extrapara: {
				"catalogID": _object.id,
				"userID": _uid,
				"period": $selectPeriod.val(),
				"year": _year.currentYear
			},
			$container: $(".vw-content-container"),
			heightDiff: 130,
			dataURL: VW_INTERFACE.WEBSERVICE.CollectionManage("LoadData"),
			submitURL: VW_INTERFACE.WEBSERVICE.CollectionManage("InsertData"),
			saveURL: VW_INTERFACE.WEBSERVICE.CollectionManage("UpdateData"),
			deleteURL: VW_INTERFACE.WEBSERVICE.CollectionManage("DeleteData"),
		});

		if(_table.hasHtml) {
			$edittable.vw_edittable('ajaxLoadReportData', "html/" + _table.id + ".html", _table.id, _table.text, 1);
		} else {
			$edittable.vw_edittable('ajaxLoadTableData', _table.id, _table.text, 1);
		}

		_loadedNodeID = _table.id;
	}

	function InitTab3() {
//		if(!_passCheck) {
//			$alertMsg.html("请上传该数据对应的附件。");
//		}

		$tableAttach.vw_edittable('destroy');

		if(!_table) {
			return;
		}

		var html = [
			'<button type="button" id="btn_attachUp" class="btn btn-primary"><i class="fa fa-upload"></i> 上传</button>',
			'<button type="button" id="btn_attachDown" class="btn btn-primary"><i class="fa fa-download"></i> 下载</button>',
			'<a download="" href="" id="down" target="_blank"></a>',
			'<button type="button" id="btn_attachDelete" class="btn btn-danger"><i class="fa fa-trash-o"></i> 删除</button>'
		].join('');

		var operate = {
			field: 'details',
			title: '操作',
			events: {
				'click .fn_data': function(e, value, row, index) {
					downloadFile(row[_idField])
				}
			},
			formatter: '<a class="fn_data tr_link" href="#" data-toggle="tooltip" title="查看"><i class="fa fa-clipboard"></i></a>'
		}

		$tableAttach.vw_edittable({
			type: "table",
			showNewData: false,
			showErrorlog: false,
			showEdit: false,
			ExtraTools: html,
			operate: operate,
			extrapara: {
				"catalogID": _object.id,
				"userID": _uid,
				"period": $selectPeriod.val(),
				"year": _year.currentYear
			},
			$container: $(".vw-content-container"),
			heightDiff: 130,
			dataURL: VW_INTERFACE.WEBSERVICE.CollectionManage("ExamineAnnex"),
			onInitialized: function() {
				$('#btn_attachUp').click(fn_file_up);
				$('#btn_attachDown').click(fn_file_down);
				$('#btn_attachDelete').click(fn_file_delete);
			},
			onAllEvents: function() {
				$('#btn_attachUp').prop('disabled', _passCheck);
				$('#btn_attachDown').prop('disabled', !$tableAttach.vw_edittable('getSelections').length);
				$('#btn_attachDelete').prop('disabled', !($tableAttach.vw_edittable('getSelections').length && !_passCheck));
			}
		}).vw_edittable('ajaxLoadTableData', _table.id, _table.text, 1);
		_idField = $tableAttach.vw_edittable('getOptions').idField;
	}

	function InitTab4() {
		$formMeta.empty();

		if(!_table) {
			return;
		}

		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.CollectionManage("ExamineMeta"),
			type: 'GET',
			dataType: 'json',
			data: {
				"catalogID": _object.id,
				"table": _table.id,
				"userID": _uid,
				"period": $selectPeriod.val(),
				"year": _year.currentYear
			},
		}, function(e) {
			$formMeta.append('<form class="form-horizontal"></form>');
			var valiFields = {};
			$.each(e.reportMeta, function(k, section) {
				var html = '<p class="form-section" style="padding-top:10px" ><span class="form-span meta-section" style="font-weight:bold">' + section.type + '</span></p>';
				var data = section.data;
				for(var i = 0; i < data.length; i++) {
					html += '<div class="form-group">';
					html += '<label class="col-xs-3 control-label">' + data[i].chField + ': </label>';
					html += '<div class="col-xs-8">';
					var disabled = data[i].isEdit && !_passCheck ? "" : "disabled";
					switch(data[i].type) {
						case "number":
							html += '<input type="number" class="form-control" name="' + data[i].egField + '" id="' + data[i].chField + '" value="' + data[i].value + '"' + disabled + '/>';
							break;
						case "string":
							html += '<input type="text" placeholder="请输入..." class="form-control" name="' + data[i].egField + '" id="' + data[i].chField + '" value="' + data[i].value + '"' + disabled + '/>';
							break;
						case "textarea":
							html += '<textarea placeholder="请输入..." class="form-control" name="' + data[i].egField + '" id="' + data[i].chField + '" ' + disabled + '>' + data[i].value + '</textarea>';
							break;
						case "":
							html += '<input type="text" placeholder="请输入..." class="form-control" name="' + data[i].egField + '" id="' + data[i].chField + '" value="' + data[i].value + '"' + disabled + '/>';
							break;
						case "number_dic":
							html += '<select class="form-control" name="' + data[i].egField + '" style="width:100%;"' + disabled + '></select>';
							break;
						case "date":
							var dateValue = data[i].value ? data[i].value : vw_static.getNowDate();
							html += '<input type="date" class="form-control" name="' + data[i].egField + '" id="' + data[i].chField + '" value="' + dateValue + '"' + disabled + '/>';
							break;
						default:
					}
					html += '</div></div>';

					valiFields[data[i].egField] = {
						validators: {
							notEmpty: {
								message: data[i].chField + '不能为空'
							}
						}
					}
				}
				$formMeta.find('form').append(html);

				$.each(data, function(k, val) {
					if(val.type == "number_dic") {
						$("select[name = '" + val.egField + "']").select2({
							data: val.values,
							placeholder: "请选择...",
							tags: true,
							language: "zh-CN",
							allowClear: true,
						});
						$("select[name = '" + val.egField + "']").val(val.value).trigger('change');
					}
				});
			});

			$formMeta.find('form').append(['<div class="form-group">',
				'	<div class="col-sm-offset-5 col-sm">',
				'		<button id="btn_submit" type="button" class="btn btn-success">提交</button>',
				'	</div>',
				'</div>'
			].join(''));

			var $submit = $("#btn_submit");
			$submit.prop('disabled', _passCheck);
			if(!_passCheck) {
//				$alertMsg.html('请确认数据、附件和元数据均已填写正确，点击“提交”按钮提交数据后会进入审核环节，请注意查看站内信。');
				valiform($submit, valiFields);
			}

			resize();
		});
	}

	function valiform($submit, fields) {
		var vali = $formMeta.find('form').bootstrapValidator({
			message: '输入的内容无效',
			feedbackIcons: {
				valid: 'glyphicon glyphicon-ok',
				invalid: 'glyphicon glyphicon-remove',
				validating: 'glyphicon glyphicon-refresh'
			},
			fields: fields
		});

		vali.on('success.form.bv', function(e) {
			if(vali) {
				vali.bootstrapValidator('destroy')
			}

			var values = {};
			var controls = $("#form_meta form .form-control");
			for(var i = 0; i < controls.length; i++) {
				var filedname = $(controls[i]).attr("name");
				values[filedname] = $(controls[i]).val();
			}
			values = JSON.stringify(values);

			vw_common.customAjax({
				url: VW_INTERFACE.WEBSERVICE.CollectionManage("SaveMeta"),
				type: 'POST',
				dataType: 'json',
				data: {
					"catalogID": _object.id,
					"table": _table.id,
					"meta": values,
					"userID": _uid,
					"period": $selectPeriod.val(),
					"year": _year.currentYear
				},
			}, function() {
				$.Notify({
					caption: "成功",
					content: "元数据已保存",
					type: "success"
				});
				vw_common.customAjax({
					url: VW_INTERFACE.WEBSERVICE.CollectionManage("SubmitData"),
					type: 'POST',
					dataType: 'json',
					data: {
						"catalogID": _object.id,
						"table": _table.id,
						"meta": values,
						"userID": _uid,
						"period": $selectPeriod.val(),
						"year": _year.currentYear
					},
				}, function() {
					$.Notify({
						caption: "成功",
						content: "数据提交成功",
						type: "success"
					});
				});
			});
		});

		$submit.on('click', function() {
			vali.bootstrapValidator('validate');
		});
	}

	function btn_reupload() {
		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.CollectionManage("ApplyReport"),
			type: 'GET',
			dataType: 'json',
			data: {
				"catalogID": _object.id,
				"table": _table.id,
				"userID": _uid,
				"period": $selectPeriod.val(),
				"year": _year.currentYear
			},
		}, function(e) {
			$.Notify({
				caption: "成功",
				content: "申请信息已发送，请耐性等待管理员回复",
				type: "success"
			});
		});
	}

	function fn_file_up() {
		bDialog.open({
			title: '上传附件',
			dom: '<div class="file-loading"><input id="inputfile" type="file" multiple="multiple"></div>',
			dialogMaxButton: false,
			customClass: 'blue',
			width: 600,
			height: 450,
			onShow: function() {
				$("#inputfile").fileinput({
					uploadUrl: VW_INTERFACE.WEBSERVICE.CollectionManage("AnnexUp"),
					language: 'zh',
					uploadExtraData: {
						"catalogID": _object.id,
						"userID": _uid,
						"table": _table.id,
						"period": $selectPeriod.val(),
						"year": _year.currentYear
					},
					maxFileCount: 10,
					uploadAsync: false
				}).on("fileuploaded", function(event, data) {
					bDialog.close({
						result: data.response
					});
				}).on('filebatchuploadsuccess', function(event, data, previewid, index) {
					bDialog.close({
						result: true
					});
				}).on('filebatchuploaderror', function(event, data, previewid, index) {
					bDialog.close({
						result: false
					});
				});
			},
			callback: function(data) {
				if(data.results) {
					if(data.results[0].result) {
						$.Notify({
							caption: "成功",
							content: "附件上传成功",
							type: "success"
						});
						InitTab3();
					} else {
						$.Notify({
							caption: "错误",
							content: "附件上传失败",
							type: "alert"
						});
					}
				}
			}
		});
	}

	function fn_file_down() {
		var id = $.map($tableAttach.vw_edittable('getSelections'), function(row) {
			return row[_idField];
		});
		downloadFile(id.join(','));
	}

	function downloadFile(id) {
		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.CollectionManage("AnnexDown"),
			type: 'GET',
			dataType: 'json',
			data: {
				id: id
			},
		}, function(e) {
			for(var i = 0; i < e.path.length; i++) {
				var a = document.getElementById("down");
				a.download = e.path[i].split("/").pop();
				a.href = e.path[i];
				a.click();
			}
		});
	}

	function fn_file_delete() {
		var id = $.map($tableAttach.vw_edittable('getSelections'), function(row) {
			return row[_idField];
		});

		bDialog.alert('确定删除该文件?', function(e) {
			vw_common.customAjax({
				url: VW_INTERFACE.WEBSERVICE.CollectionManage("AnnexDelete"),
				type: 'GET',
				dataType: 'json',
				data: {
					id: id.join(',')
				},
			}, function(e) {
				InitTab3();
				$.Notify({
					caption: "成功",
					content: "数据已删除",
					type: "success"
				});
			});

		}, {
			messageType: 'confirm',
			cancel: function() {}
		})
	}

	return {
		init: Init
	}
})